package com.zhkj.txg.module.mine.adapter

import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.ShopActivity
import com.zhkj.txg.module.mine.entity.CollectionEntity
import com.zhkj.txg.module.mine.ui.CheckStatusEntity
import com.zhkj.txg.utils.ImageUtils

class CollectionShopAdapter(
    private val onCheckChange: (checkStatus: CheckStatusEntity) -> Unit
) : BaseQuickAdapter<CollectionEntity, CollectShopViewHolder>(R.layout.item_collection_shop), LoadMoreModule {

    init {
        setOnItemClickListener { _, _, position ->
            if (editMode) {
                // 值取反
                data[position].shops?.selected = data[position].shops?.selected?.not() ?: false
                // 刷新视图
                notifyItemChanged(position)
                // 刷新状态
                refreshCheckStatus()
                // 回调,可刷新全选按钮状态
                onCheckChange(checkStatus)
            } else data[position].shops?.let {// 跳转商店页面
                if (it.id > 0) ShopActivity.open(context, it.shopName, it.id.toInt())
            }
        }
    }

    /**
     * 判断UI是否需要进入编辑模式
     */
    var editMode = false
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    /**
     * 选中状态容器
     */
    val checkStatus = CheckStatusEntity()

    override fun onItemViewHolderCreated(viewHolder: CollectShopViewHolder, viewType: Int) {
        with(viewHolder.getView<RecyclerView>(R.id.rvCollectionShop)) {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = viewHolder.productAdapter
        }
    }

    override fun convert(helper: CollectShopViewHolder, item: CollectionEntity) {
        item.shops?.let { shop ->
            val imageView = helper.setText(R.id.tvCollectShopName, shop.shopName)
                .setText(R.id.tvCollectionFansCount, "${shop.collectCount}人关注")
                .setText(R.id.tvCollectionGoodsCount, "在售商品${shop.goodsCount}")
                .setGone(R.id.ivCheck, !editMode)
                .setGone(R.id.tvCollectionShopWeek, !shop.weekNew)
                .getView<ImageView>(R.id.ivCollectShop)
            ImageUtils.loadCircleImage(context, imageView, shop.shopImg)
            helper.productAdapter.replaceData(shop.goods)
            helper.itemView.isSelected = shop.selected
        }
    }

    fun refreshCheckStatus(
        needCheckAll: Boolean = false,
        checkAll: Boolean = false
    ): CheckStatusEntity {
        var checkAllTemp = true
        var checkAny = false
        data.forEach {
            // 如果需要设置全选，就先设置全选
            if (needCheckAll) it.shops?.selected = checkAll
            // 判断是否有全选，或者选中一个
            if (it.shops?.selected == true) checkAny = true
            else checkAllTemp = false
        }
        // 如果设置了全选，刷新列表
        if (needCheckAll) notifyDataSetChanged()
        return checkStatus.apply {
            this.allCheck = checkAllTemp
            this.checkAny = checkAny
        }
    }

    /**
     * 获取所有选中商品的id,用','隔开
     */
    fun getCheckedShopsId(): String {
        return if (checkStatus.checkAny) {
            buildString {
                for (product in data)
                    if (product.shops?.selected == true) append(product.id).append(',')
                if (length > 0) deleteCharAt(lastIndex)
            }
        } else ""
    }
}

class CollectShopViewHolder(view: View) : BaseViewHolder(view) {
    val productAdapter = CollectionShopGoodsAdapter()
}